package com.hulei.studyproject.nacos.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.hulei.studyproject.druid.*;
import com.hulei.studyproject.druid.datasourcewrapper.DruidAlphaDataSourceWrapper;
import com.hulei.studyproject.druid.datasourcewrapper.DruidBetaDataSourceWrapper;
import com.hulei.studyproject.druid.datasourcewrapper.DruidMasterDataSourceWrapper;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.HashMap;
import java.util.Map;

/**
 * nacos数据源配置类
 * @Title: NacosConfigConfiguration
 * @Description: TODO
 * @author: hulei
 * @date: 2023/8/2 10:53
 * @Version: 1.0
 */
@EnableAutoConfiguration
@Configuration
public class NacosDataSourceConfiguration {
    @Bean(initMethod = "init")
    @ConditionalOnMissingBean(DruidMasterDataSourceWrapper.class)
    @RefreshScope
    public DruidDataSource masterDataSource() {
        return new DruidMasterDataSourceWrapper();
    }

    @Bean(initMethod = "init")
    @ConditionalOnMissingBean(DruidAlphaDataSourceWrapper.class)
    @RefreshScope
    public DruidDataSource alphaDataSource() {
        return new DruidAlphaDataSourceWrapper();
    }

    @Bean(initMethod = "init")
    @ConditionalOnMissingBean(DruidBetaDataSourceWrapper.class)
    @RefreshScope
    public DruidDataSource betaDataSource() {
        return new DruidBetaDataSourceWrapper();
    }

    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dynamicDataSource(@Qualifier("masterDataSource") DruidDataSource masterDataSource, @Qualifier("alphaDataSource") DruidDataSource alphaDataSource,@Qualifier("betaDataSource") DruidDataSource betaDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
        targetDataSources.put(DataSourceType.ALPHA.name(), alphaDataSource);
        targetDataSources.put(DataSourceType.BETA.name(), betaDataSource);
        return new DynamicDataSource(masterDataSource, targetDataSources);
    }
}
